<template>
  <van-nav-bar
    title="购物车"
    left-text="返回"
    left-arrow
    @click-left="
      () => {
        $router.push('/');
      }
    "
    fixed
  />

  <div style="margin-top: 40px"></div>

  <van-empty
    v-if="!usercarts.length"
    image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png"
    image-size="80"
    description="没有商品"
  >
    <router-link to="/">去购买</router-link>
  </van-empty>

  <div v-else>
    <van-swipe-cell v-for="item in usercarts">
      <van-card :num="item.number" 
         :price="item.goods.goods_price"
        :title="item.goods.goods_name"
        class="goods-card"
        :thumb="item.goods.goods_small_logo">
        <!-- 复选框 -->
         <template #thumb>
            <div style="display: flex; width: 100px;">
                <!-- 复选框 -->
                 <van-checkbox v-model="item.checked"></van-checkbox>
                <!-- 图片 -->
                  <van-image style="width: 80px;" :src="item.goods.goods_small_logo" alt=""/>
            </div>
               
         </template>

        <!-- 手写插槽 -->
        <template #num>

          <!-- 步进器 -->
          <van-stepper
            v-model="item.number"
            theme="round"
            button-size="22"
            disable-input/>

        </template>

      </van-card>


      <template #right>
        <van-button
          style="height: 100%"
          square
          text="删除"
          @click="delItems(item.id)"
          type="danger"
          class="delete-button"
        />
      </template>

    </van-swipe-cell>
  </div> 

  <!-- 动作栏 -->
   <van-submit-bar :price="allprice" button-text="提交订单" @submit="onSubmit">
  <van-checkbox v-model="selectAllCart">全选</van-checkbox>
   </van-submit-bar>
</template>

<script setup>
import { computed, ref } from "vue";
import { useCounterStore } from "@/store/ceat";  
const store = useCounterStore();
let usercarts=ref([])
const data=()=>{
    let username = localStorage.getItem("username");
   usercarts.value = store.ceat.filter((item) => item.username == username);
}
data()
// 执行删除
const delItems=(id)=>{
    store.delCart(id)
    // 重新渲染
    data()
}
// 全选计算综合
const selectAllCart=computed ({
    // 获取
    get(){
        if(usercarts.value.length==0){
            return false
        }else{
            return usercarts.value.every(item=>item.checked)
        }
    },
    set(val){

        // 复选所有状态
        usercarts.value.forEach(item=>item.checked=val)
    }
})

// 总价
const allprice =computed(()=>{
    let allprice=0
    // 随机选中的商品
    let cartok=usercarts.value.filter(item=>item.checked)
    cartok.forEach(item=>{
        allprice+=item.number*item.goods.goods_price
    })
    return allprice*100
})
// 跳转
import { useRouter } from 'vue-router'
let router = new useRouter()
const onSubmit = ()=>{
  router.push('/payok')
}
</script>

<style lang="scss" scoped>
</style>